import base64
import io
import json
import os
from PIL import Image


def read_json(json_file):
    with open(json_file, 'r') as f:
        load_dict = json.load(f)
    f.close()
    return load_dict


json_file_path = 'D:\\data\\train_data\\yolo\\id_card\\train\\labels_json\\IMG_20240518_110216.json'  # 替换为你的JSON文件路径
json_data = read_json(json_file_path)
imageWidth = json_data['imageWidth']
imageHeight = json_data['imageHeight']
imagePath = json_data['imagePath']
imageData = json_data['imageData']



#

def convert_coordinates(json_data, imageWidth, imageHeight):
    bboxes = []
    for shape in json_data['shapes']:
        # 假设每个shape是一个矩形（对于多边形，需要计算最小外接矩形）
        x1 = shape['points'][0][0]  # 左上角x坐标
        y1 = shape['points'][0][1]  # 左上角y坐标
        x2 = shape['points'][-1][0]  # 右下角x坐标（假设第一个点和最后一个点构成对角）
        y2 = shape['points'][-1][1]  # 右下角y坐标

        # 转换为归一化坐标
        x_center = (x1 + x2) / 2.0 / imageWidth
        y_center = (y1 + y2) / 2.0 / imageHeight
        bbox_w = (x2 - x1) / imageWidth
        bbox_h = (y2 - y1) / imageHeight

        bboxes.append((x_center, y_center, bbox_w, bbox_h))
    return bboxes




bboxes = convert_coordinates(json_data, imageWidth, imageHeight)
def save_to_yolo_format(bboxes, class_ids, output_file):
    with open(output_file, 'w') as f:
        for bbox, class_id in zip(bboxes, class_ids):
            # 假设class_ids是一个包含每个边界框类别索引的列表
            line = f"{int(class_id)} {bbox[0]} {bbox[1]} {bbox[2]} {bbox[3]}\n"
            f.write(line)

        # 假设你已经有一个包含类别索引的列表class_ids


class_ids = [0]  # 替换为你的类别索引列表
image_name = imagePath.split(".jpg")[0]
output_file = 'D:\\data\\train_data\\yolo\\id_card\\train\labels\\'+image_name+'.txt'  # 替换为你的输出文件路径
save_to_yolo_format(bboxes, class_ids, output_file)


# 解码imageData
# decoded_image_data = base64.b64decode(imageData)
# # 将解码后的数据转换为BytesIO对象
# image_io = io.BytesIO(decoded_image_data)
# # 使用PIL打开BytesIO对象并转换为图像对象
# image = Image.open(image_io)
# # 保存图片
# image.save('D:\\data\\train_data\\yolo\\id_card\\train\\images\\'+image_name+'.png', 'PNG')